package com.zhss.security.demospringsecurity.service;

import com.zhss.security.demospringsecurity.mapper.PersistentTokenMapper;
import lombok.AllArgsConstructor;
import org.springframework.security.web.authentication.rememberme.PersistentRememberMeToken;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @ClassName MyPersistentTokenRepository
 * @Description TODO
 * @Author leejiliang
 * @DateTime 2021/9/15 14:34
 * @Version 1.0
 */
@Service
@AllArgsConstructor
public class MyPersistentTokenService implements PersistentTokenRepository {
	private final PersistentTokenMapper persistentTokenMapper;
	@Override
	public void createNewToken(PersistentRememberMeToken token) {

		// 新增之前先判断是否有已经存在的, 如果 存在就删除他, 然后再新增, 这样就能保证记住我这个功能, 一个账号只能在一台设备上实现
		persistentTokenMapper.removeUserTokens(token.getUsername());
		persistentTokenMapper.createNewToken(token);
	}

	@Override
	public void updateToken(String series, String tokenValue, Date lastUsed) {
		persistentTokenMapper.updateToken(series, tokenValue, lastUsed);
	}

	@Override
	public PersistentRememberMeToken getTokenForSeries(String seriesId) {
		return persistentTokenMapper.getTokenForSeries(seriesId);
	}

	@Override
	public void removeUserTokens(String username) {
		persistentTokenMapper.removeUserTokens(username);
	}
}
